package com.alks.function.service.impl.biocontrol.factoryQuery;

import com.alks.common.aop.AutoPageAop;
import com.alks.common.data.thread.UserIdThread;
import com.alks.common.utils.beanutils.ArrayUtils;
import com.alks.entity.data.entity.PcCuttingDailyReport;
import com.alks.entity.data.entity.PcLotHead;
import com.alks.entity.data.page.PageRecord;
import com.alks.entity.exception.ServiceErrorException;
import com.alks.function.data.dto.biocontrol.factoryQuery.StkAccDto;
import com.alks.function.data.request.biocontrol.factoryQuery.StkAccRequest;
import com.alks.function.mapper.biocontrol.factoryQuery.PcCuttingDailyReportMapper;
import com.alks.function.mapper.chengKong.PcLotHeadMapper;
import com.alks.function.service.biocontrol.factoryQuery.IStkAccService;
import com.github.pagehelper.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author MS
 * @since 2024/11/7下午5:23
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class StkAccServiceImpl implements IStkAccService {
    private final PcCuttingDailyReportMapper reportMapper;
    private final PcLotHeadMapper lotHeadMapper;

    @Override
    @AutoPageAop
    public PageRecord<StkAccDto> temp(StkAccRequest request) {
        request.setCompanyId(UserIdThread.get().getCompanyId());
        /*查询数据*/
        List<StkAccDto> accList = reportMapper.tempQuery(request);
        Map<String, Object> sumMap = reportMapper.tempSumQuery(request);
        PageRecord<StkAccDto> record = new PageRecord<>();
        record.setOther(sumMap);
        if (request.getExportFlag()) {
        if (ArrayUtils.isEmpyt(accList)){
            throw new ServiceErrorException("暂无可导出数据");
        }
            /*补充指令部分数据*/
            accList = lotHeadMapper.stkAccExportQuery(accList);
        }else if (request.getPageSize() != -1 && request.getPageNum() != -1) {
            Page<StkAccDto> page = (Page<StkAccDto>) accList;
            record.setTotal(page.getTotal());
        }
        record.setList(accList);
        return record;
    }


    //@Async
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateForced(Integer day, int i) {
        String companyId = "BF";
        if (i==1) {
            companyId = UserIdThread.get().getCompanyId();
        }
        day = day == null||day < 1 ? 1 : day;
        while (day >= 1) {
            LocalDate now = LocalDate.now().minusDays(day);
            /*删除原有数据*/
            reportMapper.deleteByDate(companyId, now);
            List<PcCuttingDailyReport> reportList = reportMapper.forcedQuery(companyId,now);
            /*获取日志*/
            String reportListStr = reportList.stream()
                    .map(PcCuttingDailyReport::toString)
                    .collect(Collectors.joining("\n"));
            log.info("\n更新数据：\n{}", reportListStr);
            List<String> lotNoList = reportList.stream()
                    .map(PcCuttingDailyReport::getLotNo)
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());
            if (ArrayUtils.isNoEmpyt(lotNoList)) {
                List<PcLotHead> lotHeads = lotHeadMapper.selectByLotNos(lotNoList, companyId);
                if (ArrayUtils.isNoEmpyt(lotHeads)) {
                    Map<String, Float> qtyMap = lotHeads.stream()
                            .collect(Collectors.toMap(PcLotHead::getLotNo,
                                    a -> a.getOrderQty() + (a.getSurplusQty() == null ? 0 : a.getSurplusQty())));
                    StringBuilder qtyMapStr = new StringBuilder();
                    qtyMap.forEach((lotNo, qty) -> qtyMapStr.append(String.format("LotNo: %s, Qty: %.2f\n", lotNo, qty)));
                    log.info("\n指令数据：\n{}\n\n", qtyMapStr);

                }
            }
            /*更新写入数据*/
            reportMapper.forcedUp(companyId, now);
            day--;
        }
    }

}
